package com.sinoglobal.ningxia.activity.player;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.LocalMediaLoader;
import com.luck.picture.lib.model.PictureConfig;
import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.service.VersionService;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.UriUtils;
import com.yalantis.ucrop.entity.LocalMedia;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * Created by XINDZ on 2017/8/15.
 * 功能:3.3版本添加 记着开启直播前的配置页面。配置成功后点击“创建直播”来跳转到直播页面
 */

public class LiveConfigActivity extends ShareAbstractActivity implements View.OnClickListener {

    private ProgressBar pb;
    private WebView webView;
    private TextView noData;
    private String defTitle;
    private WebSettings settings;
    private String webUrl = "";

    //图片上传
    ValueCallback<Uri[]> mFilePathCallback;
    ValueCallback<Uri> mUploadFile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_config);

        openChenJInShi();//开启沉浸式
        initView();
        initData();
        initClient();
        Logger.i(webUrl);
        webView.loadUrl(webUrl);


    }

    private void initClient() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                titleView.setText(title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress < 100) {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);

                } else {
                    pb.setVisibility(View.GONE);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setTitle("提示").setMessage(message).setPositiveButton("确定", null);
                builder.setCancelable(false);
                AlertDialog dialog = builder.create();
                dialog.show();
                result.confirm();
                return true;
            }

            @Deprecated
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                mUploadFile = uploadFile;
                Logger.i("openFileChooser4.1++");
                //                //打开图片选择器
                // 先初始化参数配置，在启动相册
                FunctionConfig functionConfig = new FunctionConfig();
                functionConfig.setType(LocalMediaLoader.TYPE_IMAGE);//图片还是视频
                // unctionConfig.setMaxSelectNum(9);//最多数量
                functionConfig.setSelectMode(FunctionConfig.MODE_SINGLE);//单选/多选
                functionConfig.setShowCamera(false);//是否显示摄像头
                functionConfig.setThemeStyle(ContextCompat.getColor(LiveConfigActivity.this, R.color.red600));//设置主题颜色
                functionConfig.setEnableCrop(false);//禁止裁剪
                PictureConfig.init(functionConfig);
                PictureConfig.getPictureConfig().openPhoto(LiveConfigActivity.this, resultCallback);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mFilePathCallback = filePathCallback;
//                //打开图片选择器
                // 先初始化参数配置，在启动相册
                FunctionConfig functionConfig = new FunctionConfig();
                functionConfig.setType(LocalMediaLoader.TYPE_IMAGE);//图片还是视频
//                functionConfig.setMaxSelectNum(9);//最多数量
                functionConfig.setSelectMode(FunctionConfig.MODE_SINGLE);//单选/多选
                functionConfig.setShowCamera(false);//是否显示摄像头
                functionConfig.setThemeStyle(ContextCompat.getColor(LiveConfigActivity.this, R.color.red600));//设置主题颜色
                functionConfig.setEnableCrop(false);//禁止裁剪
                PictureConfig.init(functionConfig);
                PictureConfig.getPictureConfig().openPhoto(LiveConfigActivity.this, resultCallback);
                return true;
            }
        });
        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//
//                Logger.i("VersionService.url:"+VersionService.url);
//                try {
//                    if (VersionService.url.indexOf("tel:") == 0) {
//                        Intent call_intent = new Intent(Intent.ACTION_DIAL, Uri.parse(VersionService.url));
//                        call_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        if (call_intent != null) {
//                            startActivity(call_intent);
//                        }
//
//                    } else if (VersionService.url.contains("@")) {
//                        Intent intent = new Intent();
//                        intent.setAction(Intent.ACTION_SENDTO);
//                        intent.setData(Uri.parse(VersionService.url));
//                        startActivity(intent);
//                    } else if (VersionService.url.contains("web://live/?id=")) {//前往直播页面
//                        Intent intentLivePub = new Intent(LiveConfigActivity.this, LiveConfigActivity.class);
//                        startActivity(intentLivePub);
//                        finish();
//                    } else {
//                        webUrl = VersionService.url;
//                        view.loadUrl(VersionService.url);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                return true;
//            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.i(url);
                try {
                    if (url.indexOf("tel:") == 0) {
                        Intent call_intent = new Intent(Intent.ACTION_DIAL, Uri.parse(VersionService.url));
                        call_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (call_intent != null) {
                            startActivity(call_intent);
                        }

                    } else if (url.contains("@")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SENDTO);
                        intent.setData(Uri.parse(VersionService.url));
                        startActivity(intent);
                    } else if (url.contains("web://live/")) {//前往直播页面
                        String LiveID = url.substring(11,url.length());
                        Logger.i("前往直播页面:"+url+"    LiveID:"+LiveID);
                        Intent intentLivePub = new Intent(LiveConfigActivity.this, LivePublisherActivity.class);
                        intentLivePub.putExtra("LiveID",LiveID);
                        startActivity(intentLivePub);
                        finish();
                    } else {
                        webUrl = url;
                        view.loadUrl(url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                noData.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                webView.setVisibility(View.GONE);
                noData.setVisibility(View.VISIBLE);
            }
        });
    }

    private void initData() {
        //获取用户名密码
        String phone = SharedPreferenceUtil.getString(LiveConfigActivity.this, "username");
        String pwd = SharedPreferenceUtil.getString(mActivity, "autoPwd");
//        webUrl = ConnectionUtil.NINGXIA_LIVE_CONFIG + phone + "&pass=" + pwd;
        webUrl = "http://common.nxtv.com.cn/reporterlive/?phone=" + phone + "&pass=" + pwd;

        //默认的Title
        defTitle = getResources().getString(R.string.ningxia_tv);
        titleView.setText(defTitle);
        //清理Cooki
        CookieSyncManager.createInstance(LiveConfigActivity.this);
        CookieSyncManager.getInstance().startSync();
        CookieManager.getInstance().removeSessionCookie();
        //清理缓存
        webView.clearCache(true);
        webView.clearHistory();

        //WebView 的各种设置:支持JS,屏幕自适应,保存表单数据,预览模式加载界面
        //是否使用其内置的变焦机制,否支持使用屏幕控件或手势进行缩放,是否展现在屏幕缩放控件
        settings = webView.getSettings();
        settings.setJavaScriptEnabled(true); //支持JS
        settings.setUseWideViewPort(true);// 屏幕自适应
        settings.setSaveFormData(true);//保存表单数据
        settings.setLoadWithOverviewMode(true);//预览模式加载界面
        settings.setBuiltInZoomControls(false);//是否使用其内置的变焦机制
        settings.setSupportZoom(false);//否支持使用屏幕控件或手势进行缩放
        settings.setDisplayZoomControls(false);//是否展现在屏幕缩放控件
        settings.setPluginState(WebSettings.PluginState.ON);
    }

    private void initView() {
        titleView.setText(MContants.EMPTY_STRING);
        // 设置超过10个字，文字省略
        titleView.setSingleLine(true);
        titleView.setMaxEms(10);
        titleView.setEllipsize(TextUtils.TruncateAt.END);
        templateButtonLeft.setOnClickListener(this);
        microButtonRight.setVisibility(View.VISIBLE);
        microButtonRight.setImageResource(R.drawable.sharelogo);
        microButtonRight.setPadding(0, 0, 0, 0);

        pb = (ProgressBar) findViewById(R.id.pb_liveconfig);
        webView = (WebView) findViewById(R.id.wv_video);
        noData = (TextView) findViewById(R.id.tv_liveconfig_nodata);
    }

    /**
     * 图片回调方法
     */
    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
        @Override
        public void onSelectSuccess(List<LocalMedia> resultList) {
            Logger.i("图片回调:" + resultList.size());
            final ArrayList<Uri> uriArrayList = new ArrayList<>();
            Iterator<LocalMedia> iterator = resultList.iterator();
            while (iterator.hasNext()) {
                LocalMedia localMedia = iterator.next();
                String path = localMedia.getPath();

                Uri parse = UriUtils.getImageContentUri(LiveConfigActivity.this, path);
                Logger.i("图片路径:" + path + "**URI:" + parse);
                uriArrayList.add(parse);
            }
            int size = uriArrayList.size();
            Uri[] uris = (Uri[]) uriArrayList.toArray(new Uri[size]);
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(uris);
                mFilePathCallback = null;
            } else if (mUploadFile != null) {
                mUploadFile.onReceiveValue(uris[0]);
                mUploadFile = null;
            }

        }

    };

    @Override
    protected void onResume() {
        super.onResume();
        Logger.i("图片onResume");
        if (mFilePathCallback != null) {
            mFilePathCallback.onReceiveValue(new Uri[]{});
            mFilePathCallback = null;
        }
        if (mUploadFile != null) {
            mUploadFile.onReceiveValue(null);
            mUploadFile = null;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.setVisibility(View.GONE);
        webView.stopLoading();
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.destroy();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        finish();
    }
}
